﻿using System.Drawing;
using System.Reflection;
using ApiLib.AppStart;
using ApiLib.Utils;
using SqlSugar;

namespace ApiLib.Common.Attributes;

/// <summary>
/// Excel
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)]
public class ExcelAttribute : SugarColumn
{
    /// <summary>
    /// 名称Sheet名或者列名
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// 是否忽略
    /// </summary>
    public bool IsIgnore { get; set; }
    
    /// <summary>
    /// Excel文件
    /// </summary>
    public bool IsImage { get; set; } = false;

    /// <summary>
    /// 高度（点x20）：类上全局生效，属性上不生效
    /// </summary>
    public int Height { get; set; }

    /// <summary>
    /// 宽度（字符x256），属性上优先
    /// </summary>
    public int Width { get; set; }

    /// <summary>
    /// Header背景颜色
    /// </summary>
    public Color HeaderBackgroundColor { get; set; } = Color.White;

    /// <summary>
    /// Header字体颜色
    /// </summary>
    public Color HeaderFontColor { get; set; } = Color.Black;

    /// <summary>
    /// Header字体大小
    /// </summary>
    public double HeaderFontSize { get; set; } = 12;

    /// <summary>
    /// Header字体加粗，默认true
    /// </summary>
    public bool HeaderFontBold { get; set; } = false;

    /// <summary>
    /// Header字体斜体，默认false
    /// </summary>
    public bool HeaderFontItalic { get; set; } = false;

    /// <summary>
    /// Header字体名称
    /// </summary>
    public string HeaderFontName { get; set; } = "微软雅黑";

    /// <summary>
    /// 背景颜色
    /// </summary>
    public Color BackgroundColor { get; set; } = Color.White;

    /// <summary>
    /// 字体颜色
    /// </summary>
    public Color FontColor { get; set; } = Color.Black;

    /// <summary>
    /// 字体大小
    /// </summary>
    public double FontSize { get; set; } = 11;

    /// <summary>
    /// 字体加粗，默认false
    /// </summary>
    public bool FontBold { get; set; } = false;

    /// <summary>
    /// 斜体，默认false
    /// </summary>
    public bool FontItalic { get; set; } = false;

    /// <summary>
    /// 字体名称
    /// </summary>
    public string FontName { get; set; } = "微软雅黑";

    /// <summary>
    /// 自动换行，默认false
    /// </summary>
    public bool WrapText { get; set; } = false;

    /// <summary>
    /// 水平对齐方式
    /// </summary>
    public ExcelAttrAlign Alignment { get; set; } = ExcelAttrAlign.Left;

    /// <summary>
    /// 纵向对齐方式
    /// </summary>
    public ExcelAttrVerticalAlign VerticalAlignment { get; set; } = ExcelAttrVerticalAlign.None;

    /// <summary>
    /// 前缀：时间不生效
    /// </summary>
    public string Prefix { get; set; } = "";

    /// <summary>
    /// 后缀：时间不生效
    /// </summary>
    public string Suffix { get; set; } = "";

    /// <summary>
    /// 默认值
    /// </summary>
    public string DefaultValue { get; set; } = "";

    /// <summary>
    /// 日期格式：yyyy-MM-dd,yyyy-MM-dd HH:mm:ss
    /// </summary>
    public string DateFormat { get; set; } = "yyyy-MM-dd HH:mm:ss";

    /// <summary>
    /// 读取内容转表达式 (如: 0=男,1=女,2=未知)
    /// </summary>
    public string ReadConverterExp { get; set; } = "";

    /// <summary>
    /// 
    /// </summary>
    public ExcelAttribute() : this("")
    {
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="name"></param>
    public ExcelAttribute(string name)
    {
        this.Name = name;
    }
    
    
    /// <summary>
    /// 获取数据，将对象的数据转化成Excel的数据
    /// </summary>
    /// <param name="fieldValue"></param>
    /// <param name="propertyInfo"></param>
    /// <returns></returns>
    public object? GetData(object? fieldValue, PropertyInfo? propertyInfo = null)
    {
        var excelAttribute = this;
        if (excelAttribute.IsImage)
        {
            if (fieldValue is string filePath)
            {
                var paths = filePath.Split(",").Where(s=> !string.IsNullOrEmpty(s)).ToList();
                var datas= new List<byte[]>();
                foreach (var path in paths)
                {
                    var savePath = Path.Combine(AppContext.BaseDirectory, path);
                    if (File.Exists(savePath))
                    {
                        using var fileStream = File.OpenRead(filePath);
                        using var stream = new MemoryStream();
                        fileStream.CopyTo(stream);
                        datas.Add(stream.ToArray());
                    }
                }
                return datas;
            }
            /*if (fieldValue is FileInfo fileInfo)
            {
                using var fileStream = fileInfo.OpenRead();
                using var stream = new MemoryStream();
                fileStream.CopyTo(stream);
                return stream.ToArray();
            }*/

            return default;
        }else if (propertyInfo!=null && (propertyInfo.PropertyType == typeof(DateTime) ||
                                         propertyInfo.PropertyType == typeof(DateTime?)))
        {
            if (fieldValue is DateTime dt && dt != DateTime.MinValue)
            {
                return dt.ToString(excelAttribute.DateFormat);
            }

            return "";
        }
        else
        {
            if (!string.IsNullOrEmpty(excelAttribute.ReadConverterExp))
            {
                var strValue=fieldValue?.ToString() ?? "";
                if (!string.IsNullOrEmpty(strValue))
                {
                    var split = excelAttribute.ReadConverterExp.Split(",")
                        .FirstOrDefault(expStr => expStr.StartsWith(strValue+"="));
                    if (!string.IsNullOrEmpty(split))
                    {
                        fieldValue = split[(split.IndexOf('=') + 1)..];
                    }
                }
            }

            //默认字符串
            if (fieldValue == null && !string.IsNullOrEmpty(excelAttribute.DefaultValue))
            {
                fieldValue = excelAttribute.DefaultValue;
            }

            //前缀
            if (!string.IsNullOrEmpty(excelAttribute.Prefix))
            {
                fieldValue = excelAttribute.Prefix + fieldValue;
            }

            //后缀
            if (!string.IsNullOrEmpty(excelAttribute.Suffix))
            {
                fieldValue += excelAttribute.Suffix;
            }

            return fieldValue;
        }
    }
    
    /// <summary>
    /// 获取数据，将Excel的数据转化成对象的数据
    /// </summary>
    /// <param name="fieldValue"></param>
    /// <param name="propertyInfo"></param>
    /// <returns></returns>
    public object? ParseData(object? fieldValue, PropertyInfo? propertyInfo = null)
    {
        var excelAttribute = this;
        if (excelAttribute.IsImage)
        {
            if (fieldValue is List<byte[]> bytes)
            {
                var month = DateTime.Now.ToString("yyyyMM");
                var paths = new List<string>();
                foreach (var bs in bytes)
                {
                    var savePath = Path.Combine(AppContext.BaseDirectory,GlobalConfig.UploadPath, month);
                    if (!Directory.Exists(savePath)) Directory.CreateDirectory(savePath);
                    var fileName = Guid.NewGuid().ToString("N")+".png";
                    var filePath = Path.Combine(savePath, fileName);
                    File.WriteAllBytes(filePath, bs);
                    paths.Add(Path.Combine(GlobalConfig.UploadPath, month, fileName));
                }

                return string.Join(",",paths);
            }

            return default;
        }
        
        var strValue = fieldValue?.ToString()??"";
        if (propertyInfo!=null && (propertyInfo.PropertyType == typeof(DateTime) ||
                                         propertyInfo.PropertyType == typeof(DateTime?)))
        {
            var format = excelAttribute.DateFormat;
            if (!string.IsNullOrEmpty(strValue) && strValue.TryToDateTime(format, out var dt))
            {
                return dt;
            }

            return default;
        }
        else
        {
            //后缀
            if (!string.IsNullOrEmpty(excelAttribute.Suffix))
            {
                if (strValue.EndsWith(excelAttribute.Suffix))
                {
                    strValue = strValue[..^excelAttribute.Suffix.Length];
                }
            }

            //前缀
            if (!string.IsNullOrEmpty(excelAttribute.Prefix))
            {
                if (strValue.StartsWith(excelAttribute.Prefix))
                {
                    strValue = strValue[excelAttribute.Prefix.Length..];
                }
            }
            
            //默认字符串
            if (!string.IsNullOrEmpty(excelAttribute.DefaultValue))
            {
                if (strValue == excelAttribute.DefaultValue)
                {
                    strValue = "";
                }
            }
            
            if (!string.IsNullOrEmpty(excelAttribute.ReadConverterExp))
            {
                if (!string.IsNullOrEmpty(strValue))
                {
                    var split = excelAttribute.ReadConverterExp.Split(",")
                        .FirstOrDefault(expStr => expStr.EndsWith("="+strValue));
                    if (!string.IsNullOrEmpty(split))
                    {
                        fieldValue = split[..split.IndexOf('=')];
                    }
                }
            }
            
            return fieldValue;
        }
    }
}

/// <summary>
/// 横向对齐
/// </summary>
public enum ExcelAttrAlign
{
    /**
     * 默认，左对齐
     */
    General = 0,

    /**
     * 左对齐
     */
    Left = 1,

    /**
     * 中间对齐
     */
    Center = 2,

    /**
     * 右对齐
     */
    Right = 3,
}

/// <summary>
/// 纵向对齐
/// </summary>
public enum ExcelAttrVerticalAlign
{
    /**
     * 不对齐.
     */
    None = -1,

    /**
     * 顶部对齐
     */
    Top = 0,

    /**
     * 中间对齐
     */
    Center = 1,

    /**
     * 底部对齐
     */
    Bottom = 2,
}